import http from '@/utils/request'
import { setLocalHistories } from '@/utils/storage'
import store, { AppDispatch } from '..'
import { SeatchAction } from '../reducer/search'

export const getSuggestion =
  (value: string) => async (dispatch: AppDispatch) => {
    const res = await http.get('/v1_0/suggestion?q=' + value)
    console.log(res)
    dispatch({ type: 'seatch/saveSuggestion', payload: res.data.options })
  }

export const clearSuggestion = (): SeatchAction => ({
  type: 'seatch/clearSuggestion',
})

export const addHistory = (keyword: string): SeatchAction => {
  const { histories } = store.getState().search

  const newHistories = Array.from(new Set([keyword, ...histories]))
  if (newHistories.length > 5) newHistories.length = 5

  setLocalHistories(newHistories)

  return { type: 'seatch/saveHistory', payload: newHistories }
}

export const clearHistory = (): SeatchAction => ({
  type: 'seatch/clearHistory',
})

type SearchQuery = {
  page?: number
  per_page?: number
  q: string
}

export const getSearchResult =
  ({ page = 1, per_page = 10, q = '' }: SearchQuery) =>
  async (dispatch: AppDispatch) => {
    const res = await http.get('/v1_0/search', {
      params: { page, per_page, q },
    })
    console.log(res)
    const { results } = store.getState().search
    dispatch({
      type: 'seatch/saveResult',
      payload: [...results, ...res.data.results],
    })
    if (res.data.results.length < per_page) {
      // return Promise.reject('没有更多')
      throw new Error('没了')
    }
  }
